import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'dart:io';
import 'package:image_picker/image_picker.dart';
import 'package:intl/intl.dart';

class ChatMessage {
  final String text;
  final String? imageUrl;
  final String? giftType;
  final bool isMe;
  final DateTime time;

  ChatMessage({
    this.text = '',
    this.imageUrl,
    this.giftType,
    required this.isMe,
    required this.time,
  });
}

class ChatPage extends StatefulWidget {
  final String userId;
  final String userNickname;
  final String userAvatarUrl;

  const ChatPage({
    Key? key,
    required this.userId,
    required this.userNickname,
    required this.userAvatarUrl,
  }) : super(key: key);

  @override
  _ChatPageState createState() => _ChatPageState();
}

class _ChatPageState extends State<ChatPage> {
  final TextEditingController _textController = TextEditingController();
  final List<ChatMessage> _messages = [];
  final FocusNode _focusNode = FocusNode();
  bool _isShowingEmoji = false;
  bool _isShowingMore = false;
  final ImagePicker _imagePicker = ImagePicker();

  @override
  void initState() {
    super.initState();
    // 加载一些模拟消息
    _loadDummyMessages();
  }

  void _loadDummyMessages() {
    // 添加一些模拟消息用于展示
    final now = DateTime.now();
    
    _messages.add(ChatMessage(
      text: '你好，很高兴认识你！',
      isMe: false,
      time: now.subtract(const Duration(days: 1, hours: 2)),
    ));
    
    _messages.add(ChatMessage(
      text: '你好！我也很高兴认识你',
      isMe: true,
      time: now.subtract(const Duration(days: 1, hours: 1, minutes: 50)),
    ));
    
    _messages.add(ChatMessage(
      text: '我看了你的主页，你的照片拍得真不错！',
      isMe: false,
      time: now.subtract(const Duration(days: 1, hours: 1, minutes: 30)),
    ));
    
    _messages.add(ChatMessage(
      imageUrl: 'https://picsum.photos/seed/gift1/300/200',
      isMe: false,
      time: now.subtract(const Duration(hours: 5)),
    ));
    
    _messages.add(ChatMessage(
      text: '谢谢！这是我最近拍的一些照片',
      isMe: true,
      time: now.subtract(const Duration(hours: 4)),
    ));
    
    _messages.add(ChatMessage(
      imageUrl: 'https://picsum.photos/seed/user_photo/300/200',
      isMe: true,
      time: now.subtract(const Duration(hours: 4)),
    ));
    
    _messages.add(ChatMessage(
      giftType: 'flower',
      text: '送你一朵花！',
      isMe: false,
      time: now.subtract(const Duration(minutes: 30)),
    ));
  }

  @override
  void dispose() {
    _textController.dispose();
    _focusNode.dispose();
    super.dispose();
  }

  void _handleSubmitted(String text) {
    if (text.trim().isEmpty) return;
    
    _textController.clear();
    
    setState(() {
      _messages.add(ChatMessage(
        text: text,
        isMe: true,
        time: DateTime.now(),
      ));
    });
    
    // 滚动到底部
    Future.delayed(const Duration(milliseconds: 100), () {
      _scrollToBottom();
    });
  }

  void _scrollToBottom() {
    if (_messages.isNotEmpty) {
      _scrollController.animateTo(
        _scrollController.position.maxScrollExtent,
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeOut,
      );
    }
  }

  void _pickImage() async {
    final XFile? image = await _imagePicker.pickImage(source: ImageSource.gallery);
    if (image != null) {
      setState(() {
        _messages.add(ChatMessage(
          imageUrl: image.path,
          isMe: true,
          time: DateTime.now(),
        ));
        _isShowingMore = false;
      });
      
      // 滚动到底部
      Future.delayed(const Duration(milliseconds: 100), () {
        _scrollToBottom();
      });
    }
  }

  void _sendGift(String giftType, String giftName) {
    setState(() {
      _messages.add(ChatMessage(
        giftType: giftType,
        text: '送出了$giftName',
        isMe: true,
        time: DateTime.now(),
      ));
      _isShowingMore = false;
    });
    
    // 滚动到底部
    Future.delayed(const Duration(milliseconds: 100), () {
      _scrollToBottom();
    });
  }

  final ScrollController _scrollController = ScrollController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              widget.userNickname,
              style: const TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
            ),
            Text(
              '在线',
              style: TextStyle(
                fontSize: 12,
                color: Colors.green[400],
              ),
            ),
          ],
        ),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => Get.back(),
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.videocam_outlined),
            onPressed: () {
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(content: Text('视频通话功能开发中')),
              );
            },
          ),
          IconButton(
            icon: const Icon(Icons.more_vert),
            onPressed: () {
              _showChatOptions(context);
            },
          ),
        ],
      ),
      body: Column(
        children: [
          // 消息列表
          Expanded(
            child: GestureDetector(
              onTap: () {
                // 点击消息列表时关闭表情和更多面板
                if (_isShowingEmoji || _isShowingMore) {
                  setState(() {
                    _isShowingEmoji = false;
                    _isShowingMore = false;
                  });
                }
                // 隐藏键盘
                FocusScope.of(context).unfocus();
              },
              child: ListView.builder(
                controller: _scrollController,
                padding: const EdgeInsets.all(8.0),
                itemCount: _messages.length,
                itemBuilder: (context, index) {
                  return _buildMessageItem(_messages[index]);
                },
              ),
            ),
          ),
          
          // 分割线
          const Divider(height: 1.0),
          
          // 输入区域
          _buildInputArea(),
          
          // 表情面板
          if (_isShowingEmoji) _buildEmojiPanel(),
          
          // 更多功能面板
          if (_isShowingMore) _buildMorePanel(),
        ],
      ),
    );
  }

  Widget _buildMessageItem(ChatMessage message) {
    final isMe = message.isMe;
    
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8.0),
      child: Row(
        mainAxisAlignment: isMe ? MainAxisAlignment.end : MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (!isMe) ...[
            CircleAvatar(
              backgroundImage: NetworkImage(widget.userAvatarUrl),
              radius: 20,
            ),
            const SizedBox(width: 8),
          ],
          
          Flexible(
            child: Column(
              crossAxisAlignment: isMe ? CrossAxisAlignment.end : CrossAxisAlignment.start,
              children: [
                // 时间
                Padding(
                  padding: const EdgeInsets.only(bottom: 4.0),
                  child: Text(
                    _formatMessageTime(message.time),
                    style: TextStyle(
                      fontSize: 12,
                      color: Colors.grey[600],
                    ),
                  ),
                ),
                
                // 消息内容
                if (message.giftType != null)
                  _buildGiftMessage(message, isMe)
                else if (message.imageUrl != null)
                  _buildImageMessage(message, isMe)
                else
                  _buildTextMessage(message, isMe),
              ],
            ),
          ),
          
          if (isMe) ...[
            const SizedBox(width: 8),
            CircleAvatar(
              backgroundImage: const NetworkImage('https://picsum.photos/seed/me/100'),
              radius: 20,
            ),
          ],
        ],
      ),
    );
  }

  Widget _buildTextMessage(ChatMessage message, bool isMe) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 10.0),
      decoration: BoxDecoration(
        color: isMe ? const Color(0xFF3F51B5) : Colors.grey[200],
        borderRadius: BorderRadius.circular(18.0),
      ),
      child: Text(
        message.text,
        style: TextStyle(
          color: isMe ? Colors.white : Colors.black87,
        ),
      ),
    );
  }

  Widget _buildImageMessage(ChatMessage message, bool isMe) {
    return Container(
      constraints: BoxConstraints(
        maxWidth: MediaQuery.of(context).size.width * 0.6,
      ),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12.0),
        border: Border.all(
          color: isMe ? const Color(0xFF3F51B5) : Colors.grey[300]!,
          width: 1,
        ),
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(12.0),
        child: message.imageUrl!.startsWith('http')
            ? Image.network(
                message.imageUrl!,
                fit: BoxFit.cover,
              )
            : Image.file(
                File(message.imageUrl!),
                fit: BoxFit.cover,
              ),
      ),
    );
  }

  Widget _buildGiftMessage(ChatMessage message, bool isMe) {
    // 礼物图标映射
    final Map<String, IconData> giftIcons = {
      'flower': Icons.local_florist,
      'heart': Icons.favorite,
      'star': Icons.star,
      'gift': Icons.card_giftcard,
    };
    
    // 礼物颜色映射
    final Map<String, Color> giftColors = {
      'flower': Colors.pink[300]!,
      'heart': Colors.red,
      'star': Colors.amber,
      'gift': Colors.purple[300]!,
    };
    
    final IconData giftIcon = giftIcons[message.giftType] ?? Icons.card_giftcard;
    final Color giftColor = giftColors[message.giftType] ?? Colors.purple[300]!;
    
    return Column(
      crossAxisAlignment: isMe ? CrossAxisAlignment.end : CrossAxisAlignment.start,
      children: [
        Container(
          padding: const EdgeInsets.all(16.0),
          decoration: BoxDecoration(
            color: giftColor.withOpacity(0.2),
            borderRadius: BorderRadius.circular(16.0),
            border: Border.all(color: giftColor, width: 1),
          ),
          child: Column(
            children: [
              Icon(
                giftIcon,
                size: 48,
                color: giftColor,
              ),
              const SizedBox(height: 8),
              Text(
                message.text,
                style: TextStyle(
                  color: giftColor,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildInputArea() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 8.0),
      child: Row(
        children: [
          // 表情按钮
          IconButton(
            icon: Icon(
              _isShowingEmoji ? Icons.keyboard : Icons.emoji_emotions_outlined,
              color: Colors.grey[700],
            ),
            onPressed: () {
              setState(() {
                _isShowingEmoji = !_isShowingEmoji;
                _isShowingMore = false;
                if (_isShowingEmoji) {
                  FocusScope.of(context).unfocus();
                } else {
                  _focusNode.requestFocus();
                }
              });
            },
          ),
          
          // 文本输入框
          Expanded(
            child: Container(
              margin: const EdgeInsets.symmetric(horizontal: 8.0),
              decoration: BoxDecoration(
                color: Colors.grey[200],
                borderRadius: BorderRadius.circular(20.0),
              ),
              child: Row(
                children: [
                  Expanded(
                    child: TextField(
                      controller: _textController,
                      focusNode: _focusNode,
                      decoration: const InputDecoration(
                        hintText: '发送消息...',
                        contentPadding: EdgeInsets.symmetric(horizontal: 16.0, vertical: 10.0),
                        border: InputBorder.none,
                      ),
                      onTap: () {
                        setState(() {
                          _isShowingEmoji = false;
                          _isShowingMore = false;
                        });
                      },
                      onSubmitted: _handleSubmitted,
                    ),
                  ),
                ],
              ),
            ),
          ),
          
          // 更多按钮
          IconButton(
            icon: Icon(
              _isShowingMore ? Icons.close : Icons.add_circle_outline,
              color: Colors.grey[700],
            ),
            onPressed: () {
              setState(() {
                _isShowingMore = !_isShowingMore;
                _isShowingEmoji = false;
                FocusScope.of(context).unfocus();
              });
            },
          ),
          
          // 发送按钮
          IconButton(
            icon: const Icon(Icons.send, color: Color(0xFF3F51B5)),
            onPressed: () => _handleSubmitted(_textController.text),
          ),
        ],
      ),
    );
  }

  Widget _buildEmojiPanel() {
    // 模拟表情面板
    List<String> emojis = [
      '😀', '😃', '😄', '😁', '😆', '😅', '😂', '🤣', '😊', '😇',
      '🙂', '🙃', '😉', '😌', '😍', '🥰', '😘', '😗', '😙', '😚',
      '😋', '😛', '😝', '😜', '🤪', '🤨', '🧐', '🤓', '😎', '🤩',
    ];
    
    return Container(
      height: 200,
      padding: const EdgeInsets.all(8.0),
      color: Colors.white,
      child: GridView.builder(
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 8,
        ),
        itemCount: emojis.length,
        itemBuilder: (context, index) {
          return GestureDetector(
            onTap: () {
              _textController.text = _textController.text + emojis[index];
              // 将光标移到文本末尾
              _textController.selection = TextSelection.fromPosition(
                TextPosition(offset: _textController.text.length),
              );
            },
            child: Center(
              child: Text(
                emojis[index],
                style: const TextStyle(fontSize: 24),
              ),
            ),
          );
        },
      ),
    );
  }

  Widget _buildMorePanel() {
    return Container(
      height: 200,
      padding: const EdgeInsets.all(16.0),
      color: Colors.white,
      child: GridView.count(
        crossAxisCount: 4,
        mainAxisSpacing: 16.0,
        crossAxisSpacing: 16.0,
        children: [
          _buildMorePanelItem(Icons.image, '相册', _pickImage),
          _buildMorePanelItem(Icons.camera_alt, '拍照', () {
            ScaffoldMessenger.of(context).showSnackBar(
              const SnackBar(content: Text('拍照功能开发中')),
            );
          }),
          _buildMorePanelItem(Icons.local_florist, '鲜花', () {
            _sendGift('flower', '鲜花');
          }),
          _buildMorePanelItem(Icons.favorite, '爱心', () {
            _sendGift('heart', '爱心');
          }),
          _buildMorePanelItem(Icons.star, '星星', () {
            _sendGift('star', '星星');
          }),
          _buildMorePanelItem(Icons.card_giftcard, '礼物', () {
            _sendGift('gift', '礼物');
          }),
          _buildMorePanelItem(Icons.location_on, '位置', () {
            ScaffoldMessenger.of(context).showSnackBar(
              const SnackBar(content: Text('位置分享功能开发中')),
            );
          }),
          _buildMorePanelItem(Icons.file_copy, '文件', () {
            ScaffoldMessenger.of(context).showSnackBar(
              const SnackBar(content: Text('文件分享功能开发中')),
            );
          }),
        ],
      ),
    );
  }

  Widget _buildMorePanelItem(IconData icon, String label, VoidCallback onTap) {
    return GestureDetector(
      onTap: onTap,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Container(
            width: 50,
            height: 50,
            decoration: BoxDecoration(
              color: Colors.grey[200],
              borderRadius: BorderRadius.circular(12.0),
            ),
            child: Icon(
              icon,
              color: const Color(0xFF3F51B5),
              size: 28,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            label,
            style: TextStyle(
              fontSize: 12,
              color: Colors.grey[800],
            ),
          ),
        ],
      ),
    );
  }

  String _formatMessageTime(DateTime time) {
    final now = DateTime.now();
    final difference = now.difference(time);
    
    if (difference.inDays > 0) {
      return '${difference.inDays}天前';
    } else if (difference.inHours > 0) {
      return '${difference.inHours}小时前';
    } else if (difference.inMinutes > 0) {
      return '${difference.inMinutes}分钟前';
    } else {
      return '刚刚';
    }
  }

  void _showChatOptions(BuildContext context) {
    showModalBottomSheet(
      context: context,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(16.0)),
      ),
      builder: (BuildContext context) {
        return SafeArea(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Container(
                margin: const EdgeInsets.symmetric(vertical: 8.0),
                width: 40,
                height: 4,
                decoration: BoxDecoration(
                  color: Colors.grey[300],
                  borderRadius: BorderRadius.circular(2.0),
                ),
              ),
              ListTile(
                leading: const Icon(Icons.delete_outline, color: Colors.red),
                title: const Text('清空聊天记录'),
                onTap: () {
                  Navigator.pop(context);
                  _showClearChatConfirmDialog();
                },
              ),
              ListTile(
                leading: const Icon(Icons.block_outlined, color: Colors.orange),
                title: const Text('屏蔽此人'),
                onTap: () {
                  Navigator.pop(context);
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(content: Text('屏蔽功能开发中')),
                  );
                },
              ),
              ListTile(
                leading: const Icon(Icons.report_outlined, color: Colors.orange),
                title: const Text('举报'),
                onTap: () {
                  Navigator.pop(context);
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(content: Text('举报功能开发中')),
                  );
                },
              ),
              const SizedBox(height: 8),
            ],
          ),
        );
      },
    );
  }

  void _showClearChatConfirmDialog() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('清空聊天记录'),
          content: const Text('确定要清空与该用户的所有聊天记录吗？此操作不可撤销。'),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('取消'),
            ),
            TextButton(
              onPressed: () {
                Navigator.pop(context);
                setState(() {
                  _messages.clear();
                });
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('聊天记录已清空')),
                );
              },
              child: const Text('确定', style: TextStyle(color: Colors.red)),
            ),
          ],
        );
      },
    );
  }
}